<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../api/index.js"
import { checkblank, checkprice, checkratio } from "../util/util.js";
import { el } from "element-plus/es/locales.mjs";

const tableData = ref([]);
const checkObj = ref({
    page: 1,
    size: 10,
})
const total = ref({});

const addWinVisible = ref(false);
const addObj = ref({});

const editWinVisible = ref(false);
const editObj = ref({});
var editIndext = -1;

const formRef = ref({});

//输入建议列表
const suggestions = ref([]);
const selectedTicketId = ref(null);
//搜搜索选择列表
const ticketsOpt = ref([])
const ticketsOptS = ref([])
const getTicketsOpt = async function () {
    let resultA = await api.get("api/trec/tickets")
    ticketsOpt.value = resultA.data;
    ticketsOptS.value = [{ id: null, name: "无" }, ...ticketsOpt.value];
    console.log("TICKETSOPT:" + ticketsOpt.value);
}


//显示数据
onMounted(async function () {
    await getTicketsOpt();
    checkData();

});

const checkData = async function (val) {

    if (typeof val == "number") {
        checkObj.value.page = val;
    }
    let result = await api.get("/api/tss", checkObj.value);
    console.log(result.data.res + "!!!!!!!!!!!!111");
    //更新表格中的数据
    tableData.value = result.data.res;
    total.value = result.data.count;
};

//表单验证
const rules = reactive({

})

//添加数据
//显示窗口
const addWin = function () {
    addWinVisible.value = true;
    addObj.value = {};
}

// 这个函数在用户输入时会被调用
const querySearchAsync1 = async (queryString, cb) => {
    console.log(queryString);
    if (queryString) {
        checkObj.value.ticketsName = queryString;
    } else {
        delete checkObj.value.ticketsName;  // 移除 ticketsName 参数
    }
    // 调用后端 API，传入用户输入的 queryString
    const result = await api.get("/api/gettname", checkObj.value);
    console.log(result.data);

    // 假设后端返回的是一个数组，将其赋值给 suggestions
    // 假设后端返回的是一个包含 `id` 和 `name` 的对象数组
    suggestions.value = result.data.map(item => ({
        value: item.name, // 显示在自动补全列表中的内容
        id: item.id // 选择后传给后端的内容
    }));
    console.log(suggestions.value);
    // 调用回调函数传入建议列表
    cb(suggestions.value);
};

// 用户选择建议时的处理函数
const handleSelect1 = (item) => {
    console.log("Selected:", item);
    selectedTicketId.value = item.id; // 存储选中的 `id`
    //addObj.value.ticketsId=selectedTicketId.value;
};

// 这个函数在用户输入时会被调用
const querySearchAsync2 = async (queryString, cb) => {
    console.log(queryString);
    if (queryString) {
        checkObj.value.attractsName = queryString;
    } else {
        delete checkObj.value.attractsName;  // 移除 ticketsId 参数
    }
    // 调用后端 API，传入用户输入的 queryString
    const result = await api.get("/api/tattracts", checkObj.value);
    console.log(result.data);

    // 假设后端返回的是一个数组，将其赋值给 suggestions
    // 将数字数组转换为包含 value 属性的对象数组
    suggestions.value = result.data.map(item => ({ value: item.toString() }));
    console.log(suggestions.value);
    // 调用回调函数传入建议列表
    cb(suggestions.value);
};

// 用户选择建议时的处理函数
const handleSelect2 = (item) => {
    console.log("Selected:", item);
    state.value = item.value; // 假设每个建议项有 `value` 属性
};

//保存添加的数据
const addSave = async function () {

    formRef.value.validate(
        async (valid) => {
            if (valid) {
                addObj.value.ticketsId = selectedTicketId.value;
                console.log("哈哈哈哈哈:" + addObj.value);
                //let check = await api.get("api/tid", addObj.value)
                let check = await api.get("api/tname", addObj.value)
                let check1 = await api.get("api/aname", addObj.value)
                if (check.code == 200 && check1.code == 200) {
                    let result = await api.postjson("/api/tss", addObj.value);
                    //tableData.value.unshift(result.data);
                    if (result.code == 200) {
                        addWinVisible.value = false;
                        ElMessage({
                            type: 'success',
                            message: '添加成功',
                        });
                        checkData();
                    } else {
                        if (result.code == 409) {
                            ElMessage({
                                type: 'error',
                                message: '添加的数据已存在',
                            });
                        }

                    }

                } else {
                    ElMessage({
                        type: 'error',
                        message: '输入的票据名称或设施名不存在',
                    });
                }
            }
        }
    )
}

//删除数据
const del = function (index, row) {
    ElMessageBox.confirm(
        "确认删除？",
        "注意",
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(async function () {
            let result = await api.del("/api/tss", row.id);
            if (result.code == 200) {
                //tableData.value.splice(index, 1);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                checkData();
            } else {
                ElMessage({
                    type: 'info',
                    message: result.message
                })
            }
        }).catch(function () {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        });
}

//修改数据
const edit = function (index, row) {
    //记录修改数据的下标
    editIndext = index;
    //绑定要修改的数据
    editObj.value.id = row.id;
    //editObj.value.ticketsId=row.ticketsId;
    editObj.value.ticketsName = row.tickets.name;
    editObj.value.attractsName = row.attractsName;
    //打开对话框
    editWinVisible.value = true;
}
const editSave = async function () {
    formRef.value.validate(
        async (valid) => {
            if (valid) {
                editObj.value.ticketsId = selectedTicketId.value;
                //let check = await api.get("api/tid", editObj.value)
                let check = await api.get("api/tname", editObj.value)
                let check1 = await api.get("api/aname", editObj.value)
                if (check.code == 200 && check1.code == 200) {
                    let result = await api.putjson("/api/tss", editObj.value);
                    console.log(result.data);
                    tableData.value[editIndext] = result.data;
                    editWinVisible.value = false;
                    ElMessage({
                        type: 'success',
                        message: '修改成功',
                    });
                    checkData();
                } else {
                    ElMessage({
                        type: 'error',
                        message: '输入的票据名称或设施名不存在',
                    });
                }
            }

        }
    )
}
</script>

<template>
    <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
            <el-select v-model="checkObj.ticketsId" placeholder="票据名称" style="width: 100%;">
                <el-option v-for="item in ticketsOptS" :label="item.name" :value="item.id" />
            </el-select></el-col>
        <el-col :span="6"><el-input v-model="checkObj.attractsName" style="width: 100%" placeholder="设施名" /></el-col>
        <el-col :span="4"><el-button type="primary" @click="checkData" style="width: 100%">
                <el-icon style="vertical-align: middle">
                    <Search />
                </el-icon>
                <span style="vertical-align: middle"> 搜索 </span>
            </el-button></el-col>
        <el-col :span="4" :offset="4"><el-button type="primary" @click="addWin" style="width: 100%">
                <el-icon>
                    <CirclePlusFilled />
                </el-icon>
                <span style="vertical-align: middle"> 新增 </span>
            </el-button></el-col>
    </el-row>
    <div style="height: 500px; overflow: auto; margin-bottom: 20px;
        border-radius: 10px; /* 圆角半径 */
        margin-top: 20px; /* 上方间距 */
        padding: 10px; /* 内间距，确保内容不会紧贴边缘 */
        background-color: #fff; /* 可选：设置背景颜色 */
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 可选：添加阴影以提高视觉效果 */">
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="tickets.name" label="票据名称" min-width="120" />
            <el-table-column prop="attractsName" label="设施名" min-width="120" />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button-group>
                        <el-button type="primary" @click="edit(scope.$index, scope.row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            <span style="vertical-align: middle"> 编辑 </span>
                        </el-button>
                        <el-button type="danger" @click="del(scope.$index, scope.row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-pagination background layout="prev, pager, next" :total="total" @current-change="checkData"
        :page-size="checkObj.size"
        style="position: fixed; left: 50%; transform: translateX(-50%); bottom: 100px; z-index: 1000;" />

    <!--start 新增信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="添加类型" width="500" prop="name">
        <el-form :model="addObj" label-width="80px" :rules="rules" ref="formRef">
            <el-row justify="center">
                <el-col :span="24" style="text-align: center;">
                    <el-form-item label="票据名称">
                        <el-autocomplete v-model="addObj.ticketsName" :fetch-suggestions="querySearchAsync1"
                            @select="handleSelect1" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row justify="center">
                <el-col :span="24" style="text-align: center;">
                    <el-form-item label="设施名">
                        <el-autocomplete v-model="addObj.attractsName" :fetch-suggestions="querySearchAsync2"
                            @select="handleSelect2" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addWinVisible = false">取消</el-button>
                <el-button type="primary" @click="addSave">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end -->

    <!--start 修改信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="修改类型" width="500" prop="name">
        <el-form :model="editObj" label-width="80px" :rules="rules" ref="formRef">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="票据名称">
                        <el-autocomplete v-model="editObj.ticketsName" :fetch-suggestions="querySearchAsync1"
                            @select="handleSelect1" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="设施名">
                        <el-autocomplete v-model="editObj.attractsName" :fetch-suggestions="querySearchAsync2"
                            @select="handleSelect2" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editWinVisible = false">取消</el-button>
                <el-button type="primary" @click="editSave">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- end -->

</template>
<style></style>